package com.sprinboot_vue.blog_springboot.controller;

import com.sprinboot_vue.blog_springboot.entity.Type;
import com.sprinboot_vue.blog_springboot.repository.TypeRepository;
import com.sprinboot_vue.blog_springboot.result.Result;
import com.sprinboot_vue.blog_springboot.result.ResultInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * @author Thomas
 * @version 1.0
 * @date 2021/11/21 21:45
 */
@RestController
@RequestMapping("/type")
@Api(tags = "类别名管理")
public class TypeHandler {
    @Autowired
    private TypeRepository typeRepository;

    @PostMapping("addType/{type}")
    @ApiOperation("添加博文类型")
    public Result addType(@PathVariable("type") String type_str){
        Type type=new Type();
        type.setId(type_str.hashCode());
        type.setType(type_str);
        type.setType_number(0);
        Long hashcode=(long)type_str.hashCode();
        Optional<Type> byId = typeRepository.findById(hashcode);
        if(!byId.isPresent()){
            try{
                Type save = typeRepository.save(type);
                return Result.success().codeAndmessage("200","添加成功!");
            }catch (Exception e){
                return Result.error().codeAndmessage("404","添加失败!");
            }
        }else{
            return Result.error().codeAndmessage("404","已经存在该分类名!");
        }
    }

    @GetMapping("/findType/{page}/{pageSize}")
    @ApiOperation("分页查询分类名")
    public Result  findType(@PathVariable("page") int page,@PathVariable("pageSize") int pageSize){
        Pageable pageable= PageRequest.of(page-1,pageSize);
        return Result.success().codeAndmessage(ResultInfo.SUCCESS).date("data",typeRepository.findAll(pageable));
    }

    @DeleteMapping("/deleteTypeById/{type}")
    @ApiOperation("删除分类名字")
    public Result deleteTypeById(@PathVariable("type") String type){
        //通过hashcode值进行删除
        long id = (long)type.hashCode();
        try{
            typeRepository.deleteById(id);
            return Result.success().codeAndmessage(ResultInfo.SUCCESS);
        }catch (Exception e){
            return Result.error().codeAndmessage(ResultInfo.ERROR);
        }
    }

    @GetMapping("/findAllType")
    @ApiOperation("返回所有的类型")
    public Result findAllType(){
        List<Type> all = typeRepository.findAll();
        return Result.success().codeAndmessage(ResultInfo.SUCCESS).date("data",all);
    }
}
